// 计时器状态和配置
const timerConfig = {
    workDuration: 25 * 60, // 25分钟工作时间（秒）
    breakDuration: 5 * 60, // 5分钟休息时间（秒）
    isRunning: false,
    isBreakTime: false,
    currentTime: 25 * 60,
    interval: null,
    totalWorkTime: 0,
    sessionsCompleted: 0
};

// DOM 元素
const timerElements = {
    minutes: document.getElementById('timer-minutes'),
    seconds: document.getElementById('timer-seconds'),
    progress: document.getElementById('timer-progress'),
    startBtn: document.getElementById('start-timer'),
    pauseBtn: document.getElementById('pause-timer'),
    resetBtn: document.getElementById('reset-timer'),
    nextBreakTime: document.getElementById('next-break-time'),
    breakMinutes: document.getElementById('break-timer-minutes'),
    breakSeconds: document.getElementById('break-timer-seconds'),
    breakProgress: document.getElementById('break-timer-progress'),
    focusSessions: document.getElementById('focus-sessions'),
    totalWorkTime: document.getElementById('total-work-time'),
    statusText: document.getElementById('status-text')
};

// 更新时间显示
function updateTimerDisplay() {
    const minutes = Math.floor(timerConfig.currentTime / 60);
    const seconds = timerConfig.currentTime % 60;
    
    if (timerConfig.isBreakTime) {
        timerElements.breakMinutes.textContent = minutes.toString().padStart(2, '0');
        timerElements.breakSeconds.textContent = seconds.toString().padStart(2, '0');
        
        // 更新进度圈
        const progressPercentage = 100 - (timerConfig.currentTime / timerConfig.breakDuration * 100);
        timerElements.breakProgress.style.background = 
            `conic-gradient(var(--break-color) ${progressPercentage}%, transparent ${progressPercentage}%)`;
    } else {
        timerElements.minutes.textContent = minutes.toString().padStart(2, '0');
        timerElements.seconds.textContent = seconds.toString().padStart(2, '0');
        
        // 更新进度圈
        const progressPercentage = 100 - (timerConfig.currentTime / timerConfig.workDuration * 100);
        timerElements.progress.style.background = 
            `conic-gradient(var(--secondary-color) ${progressPercentage}%, transparent ${progressPercentage}%)`;
        
        // 更新下次休息时间
        timerElements.nextBreakTime.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }
}

// 开始计时器
function startTimer() {
    if (timerConfig.isRunning) return;
    
    timerConfig.isRunning = true;
    timerElements.startBtn.disabled = true;
    timerElements.pauseBtn.disabled = false;
    timerElements.resetBtn.disabled = false;
    
    timerElements.statusText.textContent = timerConfig.isBreakTime ? "休息中" : "专注中";
    
    // 更新状态指示器的样式和文本
    const statusIndicator = document.querySelector('.status-indicator');
    if (timerConfig.isBreakTime) {
        statusIndicator.classList.remove('working');
        statusIndicator.classList.add('breaking');
        statusIndicator.style.setProperty('--status-color', 'var(--break-color)');
    } else {
        statusIndicator.classList.add('working');
        statusIndicator.classList.remove('breaking');
        statusIndicator.style.setProperty('--status-color', '#2ecc71');
    }
    
    timerConfig.interval = setInterval(() => {
        timerConfig.currentTime--;
        
        if (!timerConfig.isBreakTime) {
            timerConfig.totalWorkTime++;
            updateStats();
        }
        
        updateTimerDisplay();
        
        if (timerConfig.currentTime <= 0) {
            clearInterval(timerConfig.interval);
            timerConfig.isRunning = false;
            
            if (timerConfig.isBreakTime) {
                // 休息结束，切换到工作模式
                timerConfig.isBreakTime = false;
                timerConfig.currentTime = timerConfig.workDuration;
                switchToWorkMode();
                playSound('work-start.mp3');
                showAchievementPopup('休息达人', '完成一次完整休息');
            } else {
                // 工作结束，切换到休息模式
                timerConfig.isBreakTime = true;
                timerConfig.currentTime = timerConfig.breakDuration;
                timerConfig.sessionsCompleted++;
                timerElements.focusSessions.textContent = timerConfig.sessionsCompleted;
                switchToBreakMode();
                playSound('break-start.mp3');
                
                // 检查是否达成成就
                if (timerConfig.sessionsCompleted === 1) {
                    showAchievementPopup('初级摸鱼师', '完成第一个专注时段');
                } else if (timerConfig.sessionsCompleted === 4) {
                    showAchievementPopup('摸鱼高手', '完成4个专注时段');
                } else if (timerConfig.sessionsCompleted === 8) {
                    showAchievementPopup('摸鱼大师', '完成8个专注时段');
                }
            }
            
            updateTimerDisplay();
            timerElements.startBtn.disabled = false;
            timerElements.pauseBtn.disabled = true;
        }
    }, 1000);
}

// 暂停计时器
function pauseTimer() {
    if (!timerConfig.isRunning) return;
    
    clearInterval(timerConfig.interval);
    timerConfig.isRunning = false;
    timerElements.startBtn.disabled = false;
    timerElements.pauseBtn.disabled = true;
    timerElements.statusText.textContent = "已暂停";
}

// 重置计时器
function resetTimer() {
    clearInterval(timerConfig.interval);
    timerConfig.isRunning = false;
    
    if (timerConfig.isBreakTime) {
        timerConfig.currentTime = timerConfig.breakDuration;
    } else {
        timerConfig.currentTime = timerConfig.workDuration;
    }
    
    updateTimerDisplay();
    timerElements.startBtn.disabled = false;
    timerElements.pauseBtn.disabled = true;
    timerElements.resetBtn.disabled = true;
    timerElements.statusText.textContent = "准备中";
}

// 切换到工作模式
function switchToWorkMode() {
    document.getElementById('work-mode-btn').classList.add('active');
    document.getElementById('break-mode-btn').classList.remove('active');
    document.getElementById('work-mode-panel').classList.add('active');
    document.getElementById('break-mode-panel').classList.remove('active');
    
    // 更新状态指示器
    const statusIndicator = document.querySelector('.status-indicator');
    statusIndicator.classList.add('working');
    statusIndicator.classList.remove('breaking');
    statusIndicator.style.setProperty('--status-color', '#2ecc71');
    timerElements.statusText.textContent = timerConfig.isRunning ? "专注中" : "准备中";
}

// 切换到休息模式
function switchToBreakMode() {
    document.getElementById('work-mode-btn').classList.remove('active');
    document.getElementById('break-mode-btn').classList.add('active');
    document.getElementById('work-mode-panel').classList.remove('active');
    document.getElementById('break-mode-panel').classList.add('active');
    
    // 更新状态指示器
    const statusIndicator = document.querySelector('.status-indicator');
    statusIndicator.classList.remove('working');
    statusIndicator.classList.add('breaking');
    statusIndicator.style.setProperty('--status-color', 'var(--break-color)');
    timerElements.statusText.textContent = timerConfig.isRunning ? "休息中" : "准备中";
    
    // 在切换到休息模式时自动开始计时
    if (!timerConfig.isRunning) {
        startTimer();
    }
}

// 更新统计数据
function updateStats() {
    const hours = Math.floor(timerConfig.totalWorkTime / 3600);
    const minutes = Math.floor((timerConfig.totalWorkTime % 3600) / 60);
    
    if (hours > 0) {
        timerElements.totalWorkTime.textContent = `${hours}h ${minutes}m`;
    } else {
        timerElements.totalWorkTime.textContent = `${minutes}m`;
    }
    
    // 计算效率（模拟数据）
    const efficiency = Math.min(95, 65 + timerConfig.sessionsCompleted * 5);
    document.getElementById('efficiency-rate').textContent = `${efficiency}%`;
    
    // 更新任务完成数
    const completedTasks = document.querySelectorAll('#task-list input[type="checkbox"]:checked').length;
    document.getElementById('tasks-completed').textContent = completedTasks;
}

// 播放提示音
function playSound(soundFile) {
    // 在实际项目中，可以添加声音文件并取消注释下面的代码
    // const audio = new Audio(`sounds/${soundFile}`);
    // audio.play();
    console.log(`播放声音: ${soundFile}`);
}

// 初始化计时器
function initTimer() {
    updateTimerDisplay();
    
    timerElements.startBtn.addEventListener('click', startTimer);
    timerElements.pauseBtn.addEventListener('click', pauseTimer);
    timerElements.resetBtn.addEventListener('click', resetTimer);
    
    // 模式切换按钮
    document.getElementById('work-mode-btn').addEventListener('click', () => {
        if (!timerConfig.isBreakTime) return;
        
        if (confirm('确定要结束休息时间吗？')) {
            timerConfig.isBreakTime = false;
            timerConfig.currentTime = timerConfig.workDuration;
            clearInterval(timerConfig.interval);
            timerConfig.isRunning = false;
            updateTimerDisplay();
            switchToWorkMode();
            timerElements.startBtn.disabled = false;
            timerElements.pauseBtn.disabled = true;
            timerElements.resetBtn.disabled = true;
        }
    });
    
    document.getElementById('break-mode-btn').addEventListener('click', () => {
        if (timerConfig.isBreakTime) return;
        
        if (confirm('确定要提前休息吗？')) {
            timerConfig.isBreakTime = true;
            timerConfig.currentTime = timerConfig.breakDuration;
            clearInterval(timerConfig.interval);
            timerConfig.isRunning = false;
            updateTimerDisplay();
            switchToBreakMode();
            timerElements.startBtn.disabled = false;
            timerElements.pauseBtn.disabled = true;
            timerElements.resetBtn.disabled = true;
        }
    });
}

// 当页面加载完成后初始化计时器
document.addEventListener('DOMContentLoaded', initTimer);
